package me.dwliu.springcloud.interceptor;

import me.dwliu.springcloud.util.UserContextHolder;
import me.dwliu.springcloud.util.UserPermissionUtil;
import me.dwliu.springcloud.vo.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

public class RestTemplateUserContextInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        User user = UserContextHolder.currentUser();
        headers.add(User.USER_ID, user.getUserId());
        headers.add(User.USER_NAME, user.getUsername());
        headers.add(UserPermissionUtil.SERVICE_NAME, request.getURI().getHost());

        return execution.execute(request, body);
    }
}
